
const vscode = require('vscode');
const fs = require('fs');
const path = require('path')

const axios = require('axios');
const crypto = require('crypto');
const YOUDAO_API_URL = 'https://openapi.youdao.com/api';

// 获取当前工作区的文件夹
const workspaceFolders = vscode.workspace.workspaceFolders;
const rootPath = workspaceFolders[0].uri.fsPath;

/**
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {
	vscode.window.showInformationMessage(`Congratulations, your extension "gn-i18n-helper" is now active!`);

	const disposable = vscode.commands.registerCommand(
		'extension.getSelectedText',  // 这个名称必须与package.json中的命令名称一致
		async () => {
			const editor = vscode.window.activeTextEditor;
			if (editor) {
				// 选中的文本
				const selection = editor.selection;
				const selectedText = editor.document.getText(selection);

				if (editor.document.languageId === 'vue') {
					const document = editor.document;
					const position = editor.selection.active; // 获取光标位置
					const lineText = document.lineAt(position.line).text; // 获取当前行文本
					const currentFileContent = document.getText(); // 获取文件内容
					
					// 默认 template，防止出现多个 template 标签
					// 使用正则表达式匹配 <javaScript> 和 </javaScript> 之间的内容
					let section = 'template';
					const javaScriptRegex = /<script>([\s\S]*?)<\/script>/i;
					const javaScriptMatch = currentFileContent.match(javaScriptRegex);
					if (javaScriptMatch && javaScriptMatch[1]) {
						const matchContent = javaScriptMatch[1].trim(); // 提取内容并去除多余空格
						if(matchContent.includes(lineText)){
							section = 'javaScript';
						}
					}

					// 处理选中的内容，截取需要搜索的文字
					let searchText = '';
					if(selectedText.includes('=')){
						searchText = selectedText.split('=')[1].replace(/"/g, "").trim();
					}else{
						searchText = selectedText;
					}

					const filePath = handlePath(rootPath, 'lang/zh.js');
					
					delete require.cache[filePath]; // 清除缓存
					let zhFileContent = require(filePath);
					const findResult = findValueInObject(zhFileContent, searchText);
					console.log('findResult:', findResult);

					if(findResult) {
						let newText = '';
						const key = findResult.key;
						if(section == 'template'){
							if(selectedText.includes('=')){
								// placeholder="验证码" -> :placeholder="$t('common.verifyCode')"
								const prop = selectedText.split('=')[0];
								newText = `:${prop}="$t('${key}')"`
							}else{
								// 验证码 -> {{$t('common.username')}}
								newText = `{{$t('${key}')}}`
							}
						}else if(section == 'javaScript'){
							// "验证码" -> this.$t('common.username')
							newText = `this.$t('${key}')`
						}
						
						if(section == 'template'){
							editor.edit(editBuilder => {
								editBuilder.replace(editor.selection, newText);
							});
						}else if(section == 'javaScript'){
							const start = selection.start;
							const end = selection.end;
							// 获取当前选中内容的前后字符位置
							const newStart = new vscode.Position(start.line, Math.max(start.character - 1, 0));
							const newEnd = new vscode.Position(end.line, Math.min(end.character + 1, document.lineAt(end.line).text.length));
							// 设置新的选择区域
							editor.selection = new vscode.Selection(newStart, newEnd);
							
							editor.edit(editBuilder => {
								editBuilder.replace(editor.selection, newText); // 替换选中的内容
							});
						}
					}else{
						const translatedText = await translateText(searchText, 'en');
						const simplifyText = simplify(translatedText);
						const translatedKey = toCamelCase(simplifyText);
						addZhWordToFile(searchText, translatedKey);
						addEnWordToFile(searchText, translatedKey, simplify(translatedText));
						addFrWordToFile(searchText, translatedKey, simplify(translatedText));
					}
				}

			} else {
				vscode.window.showInformationMessage('No active editor found.');
			}
		},
	);

	context.subscriptions.push(disposable);
}

// 添加词条到文件
async function addZhWordToFile(searchText, translatedKey) {
	// 向文件中添加翻译后的文本
	const zhFilePath = handlePath(rootPath, 'lang/zh.js');
	insertLangKey(zhFilePath, ['general', translatedKey], searchText);
}

async function addEnWordToFile(searchText, translatedKey, translatedText) {
	// 向文件中添加翻译后的文本
	const enFilePath = handlePath(rootPath, 'lang/en.js');
	insertLangKey(enFilePath, ['general', translatedKey], capitalizeFirstLetter(translatedText));
}

async function addFrWordToFile(searchText, translatedKey) {
	const translatedText = await translateText(searchText, 'fr');
	// 向文件中添加翻译后的文本
	const frFilePath = handlePath(rootPath, 'lang/fr.js');
	insertLangKey(frFilePath, ['general', translatedKey], capitalizeFirstLetter(translatedText));
}

async function translateText(text, targetLanguage) {
    const appKey = '4500b822720c859f'; // 替换为您的 App Key
    const appSecret = 'ew4ssP4NVvGAUy7SFj2bbeYc5GfNkcJM'; // 替换为您的 App Secret
    const salt = Date.now();
    const curtime = Math.floor(Date.now() / 1000);
  
    const sign = crypto.createHash('sha256')
        .update(appKey + text + salt + curtime + appSecret)
        .digest('hex');

    const response = await axios.get(YOUDAO_API_URL, {
        params: {
					q: text,
					from: 'zh-CHS',
					to: targetLanguage,
					appKey: appKey,
					salt: salt,
					sign: sign,
					signType: "v3",
					curtime: curtime,
        },
    });
    return response.data.translation[0];
}

// 处理路径
function handlePath(rootPath, filePath) {
	let finalPath = '';
	if(rootPath.includes('qtx5.0')){
		finalPath = path.join(rootPath, 'src/' + filePath);
	}else {
		finalPath = path.join(rootPath, filePath);
	}
	return finalPath;
}

// 首字母大写
function capitalizeFirstLetter(string) {
	if (!string) return string;
	return string.charAt(0).toUpperCase() + string.slice(1);
}

function toCamelCase(str) {
	// 将 - 替换为 " "
	str = str.replace(/-/g, " ");
    return str
			.split(/\s+/) // 按空格分割
			.map((word, index) => {
					if (index === 0) {
							return word.toLowerCase(); // 第一个单词小写
					}
					return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); // 其他单词首字母大写
			})
			.join('');
}

// 删除 ! ? . 等符号
function simplify(text) {
	text = text.replace(/[!?。.？！]/g, '');
	const stopWords = ['the', 'is', 'in', 'at', 'and', 'of', 'to', 'a', 'that', 'it', 'on', 'for'];
	const words = text.split(' ').filter(word => !stopWords.includes(word.toLowerCase()));
	return words.join(' ').trim(); // 返回精简后的文本
}

// This method is called when your extension is deactivated
function deactivate() {
	vscode.window.showInformationMessage(`Congratulations, your extension "gn-i18n-helper" is now active!`);
}

// 查找对象中的值
function findValueInObject(obj, targetValue, parentKey = '') {
	for (let key in obj) {
	  const value = obj[key];
	  const fullKey = parentKey ? `${parentKey}.${key}` : key;
	  if (value === targetValue) {
			return { key: fullKey, value };
	  }
	  if (value && typeof value === 'object' && !Array.isArray(value)) {
			const result = findValueInObject(value, targetValue, fullKey);
			if (result) return result;
	  }
	}
	return null; // 没找到
}

// 将对象转换为字符串
function stringifyObject(obj, indent = 2) {
	const pad = ' '.repeat(indent);
	const isValidKey = key => /^[a-zA-Z_$][\w$]*$/.test(key);
	const entries = Object.entries(obj).map(([key, value]) => {
	  const displayKey = isValidKey(key) ? key : `${key}`;
	  if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
			return `${pad}${displayKey}: ${stringifyObject(value, indent + 2)}`;
	  } else if (typeof value === 'string') {
			if(value.indexOf("'") > -1) {
				return `${pad}${displayKey}: '${value.replace(/'/g, "\\'")}'`;
			}else{
				return `${pad}${displayKey}: '${value}'`;
			}
	  } else {
			return `${pad}${displayKey}: ${value}`;
	  }
	});
  
	return `{\n${entries.join(',\n')}\n${' '.repeat(indent - 2)}}`;
}
  
// 插入对象到文件中
function insertLangKey(filePath, pathArray, value) {
	const raw = fs.readFileSync(filePath, 'utf8');
	const objectCode = raw.replace(/^module\.exports\s+=\s+/, '');
	const obj = new Function(`return ${objectCode}`)();
  
	// 设置嵌套路径
	let pointer = obj;
	for (let i = 0; i < pathArray.length - 1; i++) {
	  if (!pointer[pathArray[i]]) pointer[pathArray[i]] = {};
	  pointer = pointer[pathArray[i]];
	}
	pointer[pathArray.at(-1)] = value;
  
	const result = 'module.exports = ' + stringifyObject(obj) + ';\n';
	fs.writeFileSync(filePath, result, 'utf8');
}

module.exports = {
	activate,
	deactivate
}
